package com.education.module.login;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.education.domain.SysMenu;
import com.education.domain.User;
import com.education.framework.base.BaseController;
import com.education.framework.constants.LogConstants;
import com.education.framework.session.SessionHelper;
import com.education.framework.util.Md5Util;
import com.education.module.system.sysLogs.SysLogsServices;
import com.education.module.system.sysMenu.SysMenuServices;
import com.education.module.system.user.UserServices;

@Controller
@RequestMapping("login")
public class LoginController extends BaseController{

	@Autowired
	private UserServices userServices;
	@Autowired
	private SysLogsServices logServices;
	@Autowired
	private SysMenuServices menuServices;
	
	@RequestMapping(value = "")
	public String init(){
		
		return "/login/login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(@ModelAttribute("user") User user,ModelMap model,HttpServletRequest request){
		SessionHelper.getInstance().putUser(null);
		model.remove(MESSAGE);
		if(null == user){
			model.put(MESSAGE, "登录失败，账号或密码不正确！");
		}else if(null == user.getLoginName() || "".equals(user.getLoginName())){
			model.put(MESSAGE, "登录账号不能为空！");
		}else if(null == user.getPasswd() || "".equals(user.getPasswd())){
			model.put(MESSAGE, "登录密码不能为空！");
		}
		
		if(model.containsKey(MESSAGE)){
			return "/login/login";
		}
		User loginUser = userServices.findUserByLoginName(user.getLoginName()) ;
		if(null != loginUser && Md5Util.MD5Encode(user.getPasswd()).equals(loginUser.getPasswd())){
			//读取用户权限菜单
			List<SysMenu> menuList = menuServices.find(loginUser);
			loginUser.setMenuList(menuList);
			SessionHelper.getInstance().putUser(loginUser);
			logServices.insertLog(LogConstants.LOGIN_TYPE,"登录成功" + user.getLoginName(),request);
			return "redirect:/console";
		}else{
			model.put(MESSAGE, "账号或密码有误！");
		}
		return "/login/login";
	}
}
